package cn.com.surker.workcon.service.bcs;

import cn.com.surker.base.system.entity.SysLine;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.production.entity.vo.ProductionIndentVo;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.StringUtils;
import cn.com.surker.workcon.common.GKJDBCService;
import cn.com.surker.workcon.common.RecipeTranEntity;
import cn.com.surker.workcon.service.RecipeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;

/**
 * <p>
 * 工控上传配比接口 Mapper 接口
 * </p>
 *
 * @author admin
 * @since 2024-09-26
 */
@Slf4j
public class RecipeServiceImpl extends GKJDBCService implements RecipeService {

	@Override
	public Long uploadExpend(SysLine line, ProductionIndentVo indent, String code, String betLev, String filter, String freeze, String season,
							 Integer mixLast, String scale, String exper, String assoss, List<RecipeTranEntity> list, Date nowDate) {
		Long controlLineId = line.getControlLineId();
		//	砼或砂浆标识
		String tag = "1";
		String standTag = "14";
		String datTime = DateUtil.convertString(nowDate);
		//	坍落度
		String lands = indent.getSlumps();
		//	技术要求
		String otherReq = indent.getTech();
		String remark = indent.getRemark();
		//	砼配合比
		Map<String, Object> paramsMap = convertYaboParams(controlLineId, code, tag, betLev, filter, freeze, season, lands,
			mixLast, scale, otherReq, "", "", datTime,
			tag, remark, list, 0);
		//	砂浆配合比
		Map<String, Object> standParamsMap = convertYaboParams(controlLineId, code, standTag, betLev, filter, freeze, season, lands,
			mixLast, scale, otherReq, "", "", datTime,
			standTag, remark, list, 1);
		Long taskId = insertUploadExpend(line, paramsMap, standParamsMap);
		return taskId;
	}

	/**
	 * 上传配合比
	 *
	 * @param line
	 * @param params
	 * @return
	 */
	private Long insertUploadExpend(SysLine line, Map<String, Object> params, Map<String, Object> standParams) {
		if (params == null || params.keySet().size() == 0)
			return -1l;
		String keySql = "";
		String valSql = "";
		Object[] obj = new Object[params.keySet().size()];
		Integer index = 0;
		for (String key : params.keySet()) {
			keySql += key + ",";
			valSql += "?,";
			obj[index] = params.get(key);
			index++;
		}
		keySql = keySql.substring(0, keySql.length() - 1);
		valSql = valSql.substring(0, valSql.length() - 1);
		String sql = "insert into Recipe (" + keySql + ") values (" + valSql + ")";
		String standSql = "";
		index = 0;
		Object[] standVP = {};
		if (standParams != null && standParams.keySet().size() > 0) {
			standVP = new Object[standParams.keySet().size()];
			keySql = "";
			valSql = "";
			Object[] standObj = new Object[standParams.keySet().size()];
			Integer standIndex = 0;
			for (String key : standParams.keySet()) {
				keySql += key + ",";
				valSql += "?,";
				standVP[index] = standParams.get(key);
				index++;
			}
			keySql = keySql.substring(0, keySql.length() - 1);
			valSql = valSql.substring(0, valSql.length() - 1);
			standSql = "insert into Recipe (" + keySql + ") values (" + valSql + ")";
		}
		/*String transactionKey = line.getId() + "_" + new Date().getTime() + "";
		line.setTransactionKey(transactionKey);*/
		JdbcTemplate jdbcTemplate = JDBCTemplateCache.getLineJdbcTemplate(line);
		try {
			// JDBCTemplateCache.beginTransaction(transactionKey, 0);
			// 开启事务
			beginTransaction(line.getId());
			if (standParams != null && standParams.keySet().size() > 0 && !StringUtils.isNull(standSql)) {
				Integer code = jdbcTemplate.update(standSql, standVP);
				if (code < 1)
					return -1l;
			}
			KeyHolder keyHolder = new GeneratedKeyHolder();
			jdbcTemplate.update(new PreparedStatementCreator() {
				public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
					PreparedStatement ps = connection.prepareStatement(sql, new String[]{"ID"});
					for (int i = 0; i < obj.length; i++) {
						ps.setObject(i + 1, obj[i]);
					}
					return ps;
				}
			}, keyHolder);
			Long taskId = keyHolder.getKey().longValue();
			if (taskId > 1) {
				// JDBCTemplateCache.commitTranLine(transactionKey, 0);//提交事务
				return taskId;
			}
			return -1l;
		} catch (Exception e) {
			log.error("上传配合比失败:", e);
			// JDBCTemplateCache.rollbackLine(transactionKey, 0);//回滚事务
			return -1l;
		}
	}

	private Map<String, Object> convertYaboParams(Long controlLineId, String code, String tag, String betLev, String filter, String freeze,
												  String season, String lands, Integer mixLast, String scale,
												  String otherReq, String exper, String assoss, String datTim,
												  String flag, String note, List<RecipeTranEntity> list, Integer isStand) {
		Map<String, Object> paramsMap = new LinkedHashMap<>();
		if (isStand == 1)
			code = "R" + code;
		paramsMap.put("station", controlLineId);
		paramsMap.put("code", code);
		paramsMap.put("tag", tag);
		paramsMap.put("betLev", betLev);
		paramsMap.put("filter", filter);
		paramsMap.put("freeze", freeze);
		paramsMap.put("season", season);
		paramsMap.put("lands", lands);
		paramsMap.put("mixLast", mixLast);
		paramsMap.put("scale", scale);
		paramsMap.put("otherReq", otherReq);
		paramsMap.put("exper", exper);
		paramsMap.put("assoss", assoss);
		paramsMap.put("datTim", datTim);
		paramsMap.put("flag", flag);
		paramsMap.put("note", note);
		Integer dosageFlag = 0;//是否存在用量信息
		if (list != null && list.size() > 0) {
			List<String> keyList = new ArrayList<>();
			for (int i = 0; i < list.size(); i++) {
				RecipeTranEntity map = list.get(i);
				String materialId = StringUtils.convertString(map.getMaterialId());//材料
				String materialType = StringUtils.convertString(map.getMaterialType());//材料类型
				String controlId = StringUtils.convertString(map.getControlStorageId());//工控仓位
				Double realDosage = StringUtils.convertDouble(map.getConcreteDosage());//实际下料
				if (isStand == 1)
					realDosage = StringUtils.convertDouble(map.getStandDosage());//砂浆实际下料
				String storageId = StringUtils.convertString(map.getErpStorageId());//ERP仓位
				String materialName = StringUtils.convertString(map.getControlMaterial());//ERP仓位
				if (realDosage > 0) {//验证是否存在重复的
					String key = materialId + "_" + controlId + "_" + materialType + "_" + storageId;
					if (keyList.contains(key)) {
						realDosage = 0.0;
					} else {
						keyList.add(key);
						if (dosageFlag == 0)
							dosageFlag = 1;
					}
				} else {
					realDosage = 0.0;
				}
				String mKey = "m" + (i + 1);
				String uValue = "u" + (i + 1);
				paramsMap.put(mKey, materialName);
				paramsMap.put(uValue, realDosage);
			}
		}
		if (dosageFlag == 0)
			return null;
		return paramsMap;
	}
}
